package com.xxx.springboot.controller;

import com.xxx.springboot.pojo.entity.User;
import com.xxx.springboot.service.DemoService;
import com.xxx.springboot.service.impl.WebSocketServer;
import com.xxx.springboot.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * websocket 服务端向客户端推送消息
 */
@RestController
@RequestMapping("/api/ws")
public class WebSocketController {

	@Autowired
	private DemoService demoService;

	/**
	 * 群发消息内容（广播模式）
	 *
	 * @param message
	 * @return
	 */
	@RequestMapping(value = "/sendAll", method = RequestMethod.GET)
	public String sendAllMessage(@RequestParam(required = true) String message) {
		try {
			int onlineCount = WebSocketServer.getOnlineCount();
			message = message + ", 当前在线人数：" + onlineCount;
			WebSocketServer.BroadCastInfo(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "send message["+message+"] to all client ok";
	}

	/**
	 * 指定会话ID发消息（独立发送）
	 *
	 * @param message
	 *            消息内容
	 * @param id
	 *            连接会话ID
	 * @return
	 */
	@RequestMapping(value = "/sendOne", method = RequestMethod.GET)
	public String sendOneMessage(@RequestParam(required = true) String message,
			@RequestParam(required = true) String sessionId) {
		try {
			WebSocketServer.SendMessage(sessionId, message);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "sendOne message["+message+"] to session["+sessionId+"] ok. current time is:"+System.currentTimeMillis();
	}

	/**
	 * 测试使用业务service
	 * 由于websocket比spring先启动，导致业务service无法注入
	 *
	 * @param message
	 * @return
	 */
	@RequestMapping(value = "/testBean", method = RequestMethod.GET)
	public String testBean(@RequestParam(required = true) String userName) {
		String message = "";
		try {
			User user = demoService.getByName(userName);
			message = JsonUtil.encodeJson(user);
			WebSocketServer.BroadCastInfo(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "send message["+message+"] to all client ok";
	}

}